<?php

namespace app\api\controller;

use app\common\model\User;
use app\common\controller\Api;
use fast\Random;
use think\Db;

/**
 * Token接口
 */
class Token extends Api
{
    protected $noNeedLogin = ['getToken'];
    protected $noNeedRight = '*';

    /*
     * 获取Token
     * @path api/token/getToken
     * */
    public function getToken()
    {
        $user_id = $this->request->param("user_id");
        if(!$user_id){
            $this->error("用户id不能为空");
        }
        $this->auth->smallLogin($user_id,1);
        $data = ['userinfo' => $this->auth->getUserinfo(1)];
        $this->success(__('登录成功'), $data);
    }

    /**
     * 检测Token是否过期
     * @path api/token/check
     */
    public function check()
    {
        $token = $this->auth->getToken();
        $tokenInfo = \app\common\library\Token::get($token);
        if($tokenInfo["expiretime"] > time()){
            $userInfo = User::get($tokenInfo["user_id"]);
            if($userInfo->is_jin == '1'){
                $this->success("用户已被禁用",'',203);
            }
        }
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }

    /**
     * 刷新Token
     * @path api/token/refresh
     */
    public function refresh()
    {
        //删除源Token
        $token = $this->auth->getToken();
        \app\common\library\Token::delete($token);
        //创建新Token
        $token = Random::uuid();
        \app\common\library\Token::set($token, $this->auth->user_id, 31536000);
        $tokenInfo = \app\common\library\Token::get($token);
        Db::name("user_token")->where("user_id",$this->auth->user_id)->update(["use_token"=>$tokenInfo["token"]]);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }
}
